//ProducterConsumerTest.java
package com.ylaihui.thread1;

class MsgQueue {
    private int msgcount = 0;
    public final static int MSG_MAX = 200;
    MsgQueue(){}

    public int getMsgcount(){
        return this.msgcount;
    }
    public void addCount(){
        this.msgcount++;
    }
    public void reduceCount(){
        this.msgcount--;
    }

}

class Producter implements Runnable{
    private MsgQueue msgqueue;
    Producter(){}
    Producter(MsgQueue msgqueue){
        this.msgqueue = msgqueue;
    }
    @Override
    public void run() {
        while(true){
            synchronized (msgqueue){
                if(msgqueue.getMsgcount() < MsgQueue.MSG_MAX){
                    msgqueue.addCount();
                    msgqueue.notify();
                    System.out.println("生产产品" + msgqueue.getMsgcount());
                }
                else {
                    try {
                        msgqueue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

class Consumer implements Runnable{
    private MsgQueue msgqueue;
    Consumer(){}
    Consumer(MsgQueue msgqueue){
        this.msgqueue = msgqueue;
    }
    @Override
    public void run() {
        while(true){
            synchronized (msgqueue){
                if(msgqueue.getMsgcount() > 0) {
                    System.out.println("消费产品" + msgqueue.getMsgcount());
                    msgqueue.reduceCount();
                    msgqueue.notify();
                }else {
                    try {
                        msgqueue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

public class ProducterConsumerTest {
    public static void main(String[] args) {
        // init the message queue
        MsgQueue msgq = new MsgQueue();

        Producter p = new Producter(msgq);
        Consumer c = new Consumer(msgq);

        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);

        t1.start();
        t2.start();
    }
}
